"""
混剪任务页面

新设计的表单，包含7个主要步骤：
1. 填写商品名称 - 输入框
2. 商品的分类 - 输入框
3. 添加AI素材 - 选择文件夹
4. 添加剪辑素材 - 选择文件夹
5. 选择使用的模板 - 多选
6. 点击开始混剪 - 按钮/primary
7. 展示任务进度 - 进度条
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path
import sys
import threading
import time
import os
import asyncio

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame,
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class TriggerTaskPage(BasePage):
    """混剪任务页面"""

    def __init__(self, parent, app):
        super().__init__(parent, app)

        # 初始化模板仓库
        self.template_repo = None
        self._init_template_repository()

    def _init_template_repository(self):
        """初始化模板仓库"""
        try:
            from src.core.di import injector
            from src.repositories.jianying_template_repository import JianyingTemplateRepository
            self.template_repo = injector.get(JianyingTemplateRepository)
        except Exception as e:
            print(f"初始化模板仓库失败: {e}")
            self.template_repo = None

    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 主表单容器
        self.create_main_form()
        
        # 任务进度展示
        self.create_progress_section()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 副标题
        subtitle_label = ttk.Label(
            header_frame,
            text="创建新的视频混剪任务",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
    
    def create_main_form(self):
        """创建主表单 - 按照7个步骤设计"""
        # 表单容器
        form_container = ttk.Frame(self.frame)
        form_container.pack(fill="both", expand=True, pady=(0, DesignSystem.SPACING['md']))

        # 左侧表单区域 - 调整比例，给右侧更多空间
        form_left = ttk.Frame(form_container)
        form_left.pack(side="left", fill="both", expand=True, padx=(0, DesignSystem.SPACING['md']))

        # 1. 商品名称
        self.create_product_name_section(form_left)

        # 2. 商品分类
        self.create_product_category_section(form_left)

        # 3. AI素材
        self.create_ai_material_section(form_left)

        # 4. 剪辑素材
        self.create_edit_material_section(form_left)

        # 右侧操作区域 - 增加宽度，设置最小宽度
        form_right = ttk.Frame(form_container)
        form_right.pack(side="right", fill="both", padx=(DesignSystem.SPACING['md'], 0))

        # 设置右侧区域的最小宽度
        form_right.configure(width=400)  # 设置最小宽度为400像素

        # 5. 模板选择
        self.create_template_section(form_right)

        # 6. 开始混剪按钮
        self.create_start_button(form_right)
    
    def create_product_name_section(self, parent):
        """1. 商品名称输入"""
        section_frame = create_card_frame(parent, "📦 商品名称")
        section_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['sm']))

        # 商品名称输入
        name_container = ttk.Frame(section_frame)
        name_container.pack(fill="x", pady=DesignSystem.SPACING['xs'])

        self.product_name_var = tk.StringVar()
        name_entry = ttk.Entry(
            name_container,
            textvariable=self.product_name_var
        )
        name_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        name_entry.insert(0, "请输入商品名称...")

        # 输入框焦点事件
        def on_name_focus_in(e):
            if name_entry.get() == "请输入商品名称...":
                name_entry.delete(0, tk.END)

        def on_name_focus_out(e):
            if name_entry.get() == "":
                name_entry.insert(0, "请输入商品名称...")

        name_entry.bind("<FocusIn>", on_name_focus_in)
        name_entry.bind("<FocusOut>", on_name_focus_out)
    
    def create_product_category_section(self, parent):
        """2. 商品分类输入"""
        section_frame = create_card_frame(parent, "🏷️ 商品分类")
        section_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['sm']))

        category_container = ttk.Frame(section_frame)
        category_container.pack(fill="x", pady=DesignSystem.SPACING['xs'])

        self.category_var = tk.StringVar()
        category_entry = ttk.Entry(
            category_container,
            textvariable=self.category_var
        )
        category_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        category_entry.insert(0, "请输入商品分类...")

        # 输入框焦点事件
        def on_category_focus_in(e):
            if category_entry.get() == "请输入商品分类...":
                category_entry.delete(0, tk.END)

        def on_category_focus_out(e):
            if category_entry.get() == "":
                category_entry.insert(0, "请输入商品分类...")

        category_entry.bind("<FocusIn>", on_category_focus_in)
        category_entry.bind("<FocusOut>", on_category_focus_out)
    
    def create_ai_material_section(self, parent):
        """3. AI素材添加 - 选择文件夹"""
        section_frame = create_card_frame(parent, "🤖 AI素材")
        section_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['sm']))

        ai_container = ttk.Frame(section_frame)
        ai_container.pack(fill="x", pady=DesignSystem.SPACING['xs'])

        # 文件夹路径显示
        path_frame = ttk.Frame(ai_container)
        path_frame.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        self.ai_folder_var = tk.StringVar(value="未选择文件夹")
        ai_path_label = ttk.Label(
            path_frame,
            textvariable=self.ai_folder_var,
            style='Body.TLabel',
            foreground=DesignSystem.COLORS['text_muted'],
            relief="sunken",
            padding=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['xs'])
        )
        ai_path_label.pack(side="left", fill="x", expand=True)

        # 选择文件夹按钮
        select_ai_btn = create_secondary_button(
            path_frame,
            text="📁 选择",
            command=self.select_ai_folder
        )
        select_ai_btn.pack(side="right", padx=(DesignSystem.SPACING['xs'], 0))

    
    def create_edit_material_section(self, parent):
        """4. 剪辑素材添加 - 选择文件夹"""
        section_frame = create_card_frame(parent, "✂️ 剪辑素材")
        section_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['sm']))

        edit_container = ttk.Frame(section_frame)
        edit_container.pack(fill="x", pady=DesignSystem.SPACING['xs'])

        # 文件夹路径显示
        path_frame = ttk.Frame(edit_container)
        path_frame.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        self.edit_folder_var = tk.StringVar(value="未选择文件夹")
        edit_path_label = ttk.Label(
            path_frame,
            textvariable=self.edit_folder_var,
            style='Body.TLabel',
            foreground=DesignSystem.COLORS['text_muted'],
            relief="sunken",
            padding=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['xs'])
        )
        edit_path_label.pack(side="left", fill="x", expand=True)

        # 选择文件夹按钮
        select_edit_btn = create_secondary_button(
            path_frame,
            text="📁 选择",
            command=self.select_edit_folder
        )
        select_edit_btn.pack(side="right", padx=(DesignSystem.SPACING['xs'], 0))

    def create_template_section(self, parent):
        """5. 模板选择 - 多选"""
        section_frame = create_card_frame(parent, "🎨 选择模板")
        section_frame.pack(fill="both", expand=True, pady=(0, DesignSystem.SPACING['sm']))

        template_container = ttk.Frame(section_frame)
        template_container.pack(fill="both", expand=True, pady=DesignSystem.SPACING['xs'])

        # 模板选择说明
        ttk.Label(template_container, text="选择混剪模板 (可多选):", style='Body.TLabel').pack(anchor="w")

        # 模板列表
        template_list_frame = ttk.Frame(template_container)
        template_list_frame.pack(fill="both", expand=True, pady=(DesignSystem.SPACING['xs'], 0))

        # 模板显示区域 - 支持多选，增加高度以显示更多内容
        self.template_listbox = tk.Listbox(
            template_list_frame,
            bg=DesignSystem.COLORS['bg_card'],
            fg=DesignSystem.COLORS['text_primary'],
            selectbackground=DesignSystem.COLORS['primary'],
            font=DesignSystem.FONTS['body'],
            selectmode=tk.EXTENDED,  # 支持多选
            height=10,  # 增加高度以显示更多模板
            width=50    # 增加宽度以显示完整的模板名称
        )
        self.template_listbox.pack(side="left", fill="both", expand=True)

        # 滚动条
        template_scrollbar = ttk.Scrollbar(template_list_frame, orient="vertical",
                                          command=self.template_listbox.yview)
        self.template_listbox.configure(yscrollcommand=template_scrollbar.set)
        template_scrollbar.pack(side="right", fill="y")

        # 加载启用的模板
        self.load_enabled_templates()

        # 按钮框架
        btn_frame = ttk.Frame(template_container)
        btn_frame.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        # 刷新模板按钮
        refresh_template_btn = create_secondary_button(
            btn_frame,
            text="🔄 刷新",
            command=self.refresh_templates
        )
        refresh_template_btn.pack(side="left")

        # 全选按钮
        select_all_btn = create_secondary_button(
            btn_frame,
            text="✅ 全选",
            command=self.select_all_templates
        )
        select_all_btn.pack(side="left", padx=(DesignSystem.SPACING['xs'], 0))

    def create_start_button(self, parent):
        """6. 开始混剪按钮"""
        start_frame = ttk.Frame(parent)
        start_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['sm']))

        # 大号开始按钮
        self.start_button = create_primary_button(
            start_frame,
            text="🚀 开始混剪",
            command=self.start_mixing_task
        )
        self.start_button.pack(fill="x")

        # 按钮样式优化 - 只配置padding
        self.start_button.configure(
            padding=(DesignSystem.SPACING['md'], DesignSystem.SPACING['sm'])
        )

    def create_progress_section(self):
        """7. 任务进度展示"""
        progress_frame = create_card_frame(self.frame, "📊 任务进度")
        progress_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        progress_container = ttk.Frame(progress_frame)
        progress_container.pack(fill="x", pady=DesignSystem.SPACING['xs'])

        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            progress_container,
            variable=self.progress_var,
            maximum=100,
            mode='determinate'
        )
        self.progress_bar.pack(fill="x", pady=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['xs']))

        # 进度文字
        self.progress_label = ttk.Label(
            progress_container,
            text="等待开始...",
            style='Body.TLabel'
        )
        self.progress_label.pack(anchor="w")

        # 任务状态
        status_frame = ttk.Frame(progress_container)
        status_frame.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        ttk.Label(status_frame, text="任务状态:", style='Body.TLabel').pack(side="left")

        self.status_label = ttk.Label(
            status_frame,
            text="● 未开始",
            style='Body.TLabel',
            foreground=DesignSystem.COLORS['text_muted']
        )
        self.status_label.pack(side="left", padx=(DesignSystem.SPACING['xs'], 0))

    # 事件处理方法
    def select_ai_folder(self):
        """选择AI素材文件夹"""
        folder = filedialog.askdirectory(title="选择AI素材文件夹")
        if folder:
            self.ai_folder_var.set(folder)
            messagebox.showinfo("选择成功", f"已选择AI素材文件夹:\n{folder}")

    def clear_ai_folder(self):
        """清除AI素材文件夹选择"""
        self.ai_folder_var.set("未选择文件夹")
        messagebox.showinfo("清除成功", "已清除AI素材文件夹选择")

    def select_edit_folder(self):
        """选择剪辑素材文件夹"""
        folder = filedialog.askdirectory(title="选择剪辑素材文件夹")
        if folder:
            self.edit_folder_var.set(folder)
            messagebox.showinfo("选择成功", f"已选择剪辑素材文件夹:\n{folder}")

    def clear_edit_folder(self):
        """清除剪辑素材文件夹选择"""
        self.edit_folder_var.set("未选择文件夹")
        messagebox.showinfo("清除成功", "已清除剪辑素材文件夹选择")

    def select_all_templates(self):
        """全选模板"""
        self.template_listbox.select_set(0, tk.END)
        messagebox.showinfo("全选成功", "已选择所有模板")

    def clear_template_selection(self):
        """清除模板选择"""
        self.template_listbox.selection_clear(0, tk.END)
        messagebox.showinfo("清除成功", "已清除模板选择")

    def load_enabled_templates(self):
        """加载启用的模板"""
        try:
            if not self.template_repo:
                # 如果模板仓库不可用，显示提示信息
                self.template_listbox.insert(tk.END, "❌ 无法连接到模板数据库")
                return

            # 从数据库获取所有模板
            all_templates = self.template_repo.get_all()

            # 筛选启用的模板
            enabled_templates = [
                template for template in all_templates
                if getattr(template, 'is_enabled', True)  # 默认为启用
            ]

            if not enabled_templates:
                # 如果没有启用的模板，显示提示信息
                self.template_listbox.insert(tk.END, "📭 暂无可用模板")
                self.template_listbox.insert(tk.END, "💡 请在模板库中导入并启用模板")
                return

            # 添加启用的模板到列表
            for template in enabled_templates:
                # 格式化模板显示名称
                template_name = template.template_name or "未命名模板"
                canvas_ratio = template.canvas_ratio or "未知比例"
                segments_count = template.video_segments_count or 0

                # 构建显示文本
                display_text = f"🎨 {template_name} ({canvas_ratio}, {segments_count}段)"
                self.template_listbox.insert(tk.END, display_text)

            print(f"✅ 已加载 {len(enabled_templates)} 个启用的模板")

        except Exception as e:
            print(f"❌ 加载模板失败: {e}")
            # 显示错误信息
            self.template_listbox.insert(tk.END, "❌ 加载模板失败")
            self.template_listbox.insert(tk.END, f"错误: {str(e)}")

    def refresh_templates(self):
        """刷新模板列表"""
        self.template_listbox.delete(0, tk.END)
        self.load_enabled_templates()
        messagebox.showinfo("刷新完成", "模板列表已更新")

    def start_mixing_task(self):
        """开始混剪任务"""
        # 验证表单
        if not self.validate_form():
            return

        # 收集表单数据
        form_data = self.collect_form_data()

        # 禁用开始按钮
        self.start_button.configure(state='disabled', text="混剪中...")

        # 更新状态
        self.status_label.configure(
            text="● 正在处理",
            foreground=DesignSystem.COLORS['info']
        )

        # 启动工作流处理
        self.execute_workflow(form_data)

    def collect_form_data(self):
        """收集表单数据"""
        # 获取商品信息
        product_name = self.product_name_var.get()
        if product_name == "请输入商品名称...":
            product_name = ""

        category = self.category_var.get()
        if category == "请输入商品分类...":
            category = ""

        # 获取素材文件夹路径
        ai_folder = self.ai_folder_var.get()
        if ai_folder == "未选择文件夹":
            ai_folder = None

        edit_folder = self.edit_folder_var.get()
        if edit_folder == "未选择文件夹":
            edit_folder = None

        # 获取选中的模板
        selected_templates = self.template_listbox.curselection()
        template_names = [self.template_listbox.get(i) for i in selected_templates]

        # 构建表单数据
        form_data = {
            "product_name": product_name,
            "category": category,
            "ai_material_folder": ai_folder,
            "edit_material_folder": edit_folder,
            "selected_templates": template_names,
            "template_count": len(template_names)
        }

        return form_data

    def validate_form(self):
        """验证表单数据"""
        # 检查商品名称
        if not self.product_name_var.get() or self.product_name_var.get() == "请输入商品名称...":
            messagebox.showerror("验证失败", "请输入商品名称")
            return False

        # 检查商品分类
        if not self.category_var.get() or self.category_var.get() == "请输入商品分类...":
            messagebox.showerror("验证失败", "请输入商品分类")
            return False

        # 检查是否选择了素材文件夹
        ai_folder_selected = self.ai_folder_var.get() != "未选择文件夹"
        edit_folder_selected = self.edit_folder_var.get() != "未选择文件夹"

        if not ai_folder_selected and not edit_folder_selected:
            messagebox.showerror("验证失败", "请至少选择一个AI素材文件夹或剪辑素材文件夹")
            return False

        # 检查是否选择模板
        if not self.template_listbox.curselection():
            messagebox.showerror("验证失败", "请至少选择一个模板")
            return False

        return True

    def execute_workflow(self, form_data):
        """执行工作流处理"""
        def workflow_worker():
            try:
                print("\n" + "🚀" * 20)
                print("🚀 开始执行混剪工作流")
                print("🚀" * 20)

                # 创建工作目录
                print("📁 创建工作目录...")
                base_directory = self.create_work_directory(form_data)
                print(f"✅ 工作目录创建完成: {base_directory}")

                # 准备素材文件
                print("📂 准备素材文件...")
                self.prepare_materials(form_data, base_directory)
                print("✅ 素材文件准备完成")

                # 配置工作流参数
                print("⚙️ 配置工作流参数...")
                workflow_config = self.create_workflow_config(form_data, base_directory)

                # 打印工作流配置
                print("\n" + "=" * 60)
                print("🔧 工作流配置参数:")
                print("=" * 60)
                for key, value in workflow_config.items():
                    print(f"  {key}: {value}")
                print("=" * 60)

                print("✅ 工作流配置完成")

                # 执行工作流
                print("🔄 开始执行工作流...")
                self.run_material_workflow(workflow_config)
                print("✅ 工作流执行完成")

            except Exception as e:
                print(f"❌ 工作流执行失败: {e}")
                # 在主线程中显示错误
                error = e  # 捕获异常到局部变量
                self.frame.after(0, lambda err=error: self.handle_workflow_error(err))
                return

            # 任务完成后的处理
            data = form_data  # 捕获数据到局部变量
            self.frame.after(0, lambda d=data: self.task_completed_with_data(d))

        # 在后台线程中运行工作流
        thread = threading.Thread(target=workflow_worker)
        thread.daemon = True
        thread.start()

        # 同时启动进度模拟
        self.simulate_task_progress()

    def simulate_task_progress(self):
        """模拟任务进度"""
        def progress_worker():
            # 获取选中的模板数量
            selected_templates = self.template_listbox.curselection()
            template_count = len(selected_templates)

            steps = [
                (5, "正在验证表单数据..."),
                (15, f"正在分析商品信息: {self.product_name_var.get()}"),
                (25, f"正在扫描AI素材文件夹..."),
                (35, f"正在扫描剪辑素材文件夹..."),
                (50, f"正在加载 {template_count} 个模板..."),
                (65, "正在进行素材匹配..."),
                (80, "正在生成混剪视频..."),
                (95, "正在优化输出质量..."),
                (100, "混剪任务完成!")
            ]

            for progress, message in steps:
                time.sleep(1.5)  # 模拟处理时间
                # 在主线程中更新UI
                self.frame.after(0, lambda p=progress, m=message: self.update_progress(p, m))

            # 任务完成后的处理
            self.frame.after(0, self.task_completed)

        # 在后台线程中运行
        thread = threading.Thread(target=progress_worker)
        thread.daemon = True
        thread.start()

    def update_progress(self, progress, message):
        """更新进度显示"""
        self.progress_var.set(progress)
        self.progress_label.configure(text=message)

    def task_completed(self):
        """任务完成处理"""
        self.start_button.configure(state='normal', text="🚀 开始混剪")
        self.status_label.configure(
            text="● 已完成",
            foreground=DesignSystem.COLORS['success']
        )

        # 获取任务详情
        product_name = self.product_name_var.get()
        category = self.category_var.get()
        selected_templates = self.template_listbox.curselection()
        template_names = [self.template_listbox.get(i) for i in selected_templates]

        ai_folder = self.ai_folder_var.get()
        edit_folder = self.edit_folder_var.get()

        # 构建完成信息
        completion_info = f"""混剪任务已成功完成！

📦 商品名称: {product_name}
🏷️ 商品分类: {category}
🤖 AI素材: {'已选择' if ai_folder != '未选择文件夹' else '未选择'}
✂️ 剪辑素材: {'已选择' if edit_folder != '未选择文件夹' else '未选择'}
🎨 使用模板: {len(template_names)} 个

生成的视频文件已保存到输出目录。"""

        messagebox.showinfo("任务完成", completion_info)

    def create_work_directory(self, form_data):
        """创建工作目录"""
        # 使用商品名称作为目录名
        product_name = form_data["product_name"]
        safe_name = "".join(c for c in product_name if c.isalnum() or c in (' ', '-', '_')).rstrip()
        if not safe_name:
            safe_name = "混剪任务"

        # 创建基础工作目录
        base_dir = Path("output") / "mixing_tasks" / safe_name
        base_dir.mkdir(parents=True, exist_ok=True)

        # 创建子目录结构
        subdirs = ["未分类", "AI素材", "产品展示", "产品使用", "模特试穿", "废弃素材", "成品"]
        for subdir in subdirs:
            (base_dir / subdir).mkdir(exist_ok=True)

        return str(base_dir)

    def prepare_materials(self, form_data, base_directory):
        """准备素材文件"""
        base_path = Path(base_directory)
        uncategorized_dir = base_path / "未分类"

        # 复制AI素材到未分类目录
        if form_data["ai_material_folder"]:
            ai_folder = Path(form_data["ai_material_folder"])
            if ai_folder.exists():
                self.copy_materials(ai_folder, uncategorized_dir, "AI")

        # 复制剪辑素材到未分类目录
        if form_data["edit_material_folder"]:
            edit_folder = Path(form_data["edit_material_folder"])
            if edit_folder.exists():
                self.copy_materials(edit_folder, uncategorized_dir, "EDIT")

    def copy_materials(self, source_dir, target_dir, prefix):
        """复制素材文件"""
        import shutil

        for file_path in source_dir.rglob("*"):
            if file_path.is_file() and file_path.suffix.lower() in ['.mp4', '.avi', '.mov', '.mkv', '.jpg', '.jpeg', '.png', '.gif']:
                # 生成新文件名
                new_name = f"{prefix}_{file_path.name}"
                target_path = target_dir / new_name

                # 避免文件名冲突
                counter = 1
                while target_path.exists():
                    name_parts = file_path.stem, counter, file_path.suffix
                    new_name = f"{prefix}_{name_parts[0]}_{name_parts[1]}{name_parts[2]}"
                    target_path = target_dir / new_name
                    counter += 1

                # 复制文件
                shutil.copy2(file_path, target_path)

    def create_workflow_config(self, form_data, base_directory):
        """创建工作流配置"""
        config = {
            "base_directory": base_directory,
            "product_title": form_data["category"],
            "max_segment_duration": 3.0,
            "min_segment_duration": 1.0,
            "enable_shot_detection": True,
            "enforce_max_duration": True,
            "confidence_threshold": 0.7,
            "use_mock_ai": True,  # 使用模拟AI服务
            "move_files": True,
            "create_backup": True,
            "overwrite_existing": False,
            "classification_categories": ["AI素材", "产品展示", "产品使用", "模特试穿"]
        }

        # 打印表单数据
        print("\n" + "=" * 60)
        print("📋 收集到的表单数据:")
        print("=" * 60)
        for key, value in form_data.items():
            print(f"  {key}: {value}")
        print("=" * 60)

        return config

    def run_material_workflow(self, config):
        """运行素材工作流"""
        try:
            # 导入工作流模块
            from src.workflow.video_material_workflow import execute_material_workflow

            # 打印config参数
            print("=" * 60)
            print("🔧 工作流配置参数:")
            print("=" * 60)
            for key, value in config.items():
                print(f"  {key}: {value}")
            print("=" * 60)

            # 在新的事件循环中运行异步工作流
            import asyncio
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            try:
                result = loop.run_until_complete(
                    execute_material_workflow(
                        project_directory=config["base_directory"],
                        config=config
                    )
                )
                return result
            finally:
                loop.close()

        except Exception as e:
            raise RuntimeError(f"工作流执行失败: {e}")

    def handle_workflow_error(self, error):
        """处理工作流错误"""
        self.start_button.configure(state='normal', text="🚀 开始混剪")
        self.status_label.configure(
            text="● 执行失败",
            foreground=DesignSystem.COLORS['danger']
        )

        error_message = f"工作流执行失败:\n{str(error)}"
        messagebox.showerror("执行失败", error_message)

    def task_completed_with_data(self, form_data):
        """带数据的任务完成处理"""
        self.start_button.configure(state='normal', text="🚀 开始混剪")
        self.status_label.configure(
            text="● 已完成",
            foreground=DesignSystem.COLORS['success']
        )

        # 构建完成信息
        completion_info = f"""混剪任务已成功完成！

📦 商品名称: {form_data['product_name']}
🏷️ 商品分类: {form_data['category']}
🤖 AI素材: {'已处理' if form_data['ai_material_folder'] else '未选择'}
✂️ 剪辑素材: {'已处理' if form_data['edit_material_folder'] else '未选择'}
🎨 使用模板: {form_data['template_count']} 个

生成的视频文件已保存到输出目录。"""

        messagebox.showinfo("任务完成", completion_info)
